import Vue from 'vue';
import { getLocalLanguage } from '@xiaoe/xiaoe-i18n';
import defaultLang from './zh';
import Format from './format';
import en from './en'
import vantZh from './zh-CN';
// import vantZh from 'vant/es/locale/lang/zh-CN';
import vantEn from './en-vant';
import { Locale } from "vant";

const format = Format(Vue);
let lang = defaultLang

export const t = function (path, options) {
    let value

    const array = path.split('.');
    let current = lang;
    
    if (getLocalLanguage() && getLocalLanguage() === 'en' ) {
        current = en;
        setVantLanguage('en')
    } else {
        setVantLanguage('zh')
    }

    for (let i = 0, j = array.length; i < j; i++) {
        const property = array[i];
        value = current[property];
        if (i === j - 1) {
            return format(value, options); 
        }
        if (!value) {
            return ''; 
        }
        current = value;
    }
    return '';
};

export const use = function (l) {
    lang = l || lang;
};

// 设置Vant内置语言
const setVantLanguage = function (lang, langPak) {
    if (lang === 'en') {
        Locale.use('en', vantEn.en);
    } else if (lang && !langPak) {
        Locale.use('zh-CN', vantZh);
    } else {
        Locale.use(lang, langPak);
    }
}

if (window.EventBus) {
    window.EventBus.$on('CHANGE_XIAOE_LANGUAGE', (e) => {
        console.log('CHANGE_XIAOE_LANGUAGE e-commerce ==== >', e);
        if (e === 'en') {
            use(en)
        } else {
            use(defaultLang)
        }
    });
}

export default { use, t };
